import "reflect-metadata";
import { RequestHandler } from "express";
import { instanceMethods } from "../utils";
import { router } from "../utils/router";
type MethodType = "get" | "post";

export function Controller(rootPath?: string) {
  return function <T>(targetClass: { new (...args: any[]): T }) {
    instanceMethods(targetClass.prototype).forEach((methodname) => {
      const path = Reflect.getMetadata(
        "path",
        targetClass.prototype,
        methodname
      );
      const methodType: MethodType = Reflect.getMetadata(
        "methodType",
        targetClass.prototype,
        methodname
      );
      console.log("path---", path, methodname);
      const requestHandlerMethod: RequestHandler =
        targetClass.prototype[methodname];

      const middlewares: RequestHandler[] = Reflect.getMetadata(
        "middlewares",
        targetClass.prototype,
        methodname
      );
      if (methodType) {
        if (middlewares) {
          router[methodType](path, middlewares, requestHandlerMethod);
        } else {
          router[methodType](path, requestHandlerMethod);
          // router.get(path, requestHandlerMethod);
        }
      }
    });
  };
}
